from fastapi import APIRouter, HTTPException, Depends, Request
from typing import Any
from utils.logger import setup_logger
from models.dependencies import get_dependencies

router = APIRouter(prefix="/models", tags=["Models"])

logger = setup_logger()

@router.post("/{model_name}/load")
async def load_model_endpoint(
    model_name: str,
    dependencies: dict = Depends(get_dependencies)
):
    """Manually load a model."""
    model_manager = dependencies.get("model_manager")
    app_state = dependencies.get("app_state")
    config = dependencies.get("config")
    logger.info(f"load_model_endpoint-------------111111: {model_name}")
    if model_manager is None:
        logger.error("model_manager is None")
        raise HTTPException(500, "Internal error: model_manager not initialized")
    if app_state is None:
        logger.error("app_state is None")
        raise HTTPException(500, "Internal error: app_state not initialized")

    if model_name not in model_manager.status:
        raise HTTPException(404, "Model not found")
    await model_manager.load_model(model_name, app_state, config)
    return {"status": f"{model_name} loaded"}

@router.post("/{model_name}/unload")
async def unload_model_endpoint(
    model_name: str,
    dependencies: dict = Depends(get_dependencies)
):
    """Manually unload a model."""
    model_manager = dependencies.get("model_manager")
    app_state = dependencies.get("app_state")

    if model_manager is None:
        logger.error("model_manager is None")
        raise HTTPException(500, "Internal error: model_manager not initialized")
    if app_state is None:
        logger.error("app_state is None")
        raise HTTPException(500, "Internal error: app_state not initialized")

    if model_name not in model_manager.status:
        raise HTTPException(404, "Model not found")
    model_manager.unload_model(model_name, app_state)
    return {"status": f"{model_name} unloaded"}

@router.get("/status")
async def get_model_status(
    dependencies: dict = Depends(get_dependencies)
):
    """Get model loading status."""
    model_manager = dependencies.get("model_manager")

    if model_manager is None:
        logger.error("model_manager is None")
        raise HTTPException(500, "Internal error: model_manager not initialized")

    return model_manager.get_status()